﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Weapon : MonoBehaviour
{
    public GameObject m_weapon;

    [SerializeField]private bool is_weapon;

    public Animator m_animator;

    public Transform m_attackaTar;

    public const float m_attackSpeed = 1f;

    public const float m_attackAroudn = 1f;//攻击范围

    private GameControl game_ctrl;
    // Start is called before the first frame update

    void Start()
    {
        m_weapon = GameObject.Find("Pl_Sword");
        m_weapon.GetComponent<Renderer>().enabled = false;
        is_weapon = false;
        m_animator = GetComponent<Animator>();
        game_ctrl = GameObject.FindWithTag("GameCtrl").GetComponent<GameControl>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    void Remove()  
    {
        m_weapon.GetComponent<Renderer>().enabled = false;
        is_weapon = false;
        m_attackaTar = null;
        GetComponent<GridMove>().IsAttacking = false;
        // 为了同步层上的动画（防止左右手的摆动不匹配）
        // 重置状态（不执行补间）
        m_animator.SetBool("is_attacking",false);
        m_animator.SetTrigger("end_attack");
        m_animator.Play("idle", 0);
        m_animator.Play("idle", 1);
        GameObject.FindWithTag("Player").GetComponent<PlayerControl>().SetInvincible(false);
    }
    // 能够攻击吗？
    public bool CanAutoAttack()
    {
        if (is_weapon)
            return true;
        else
            return false;
    }
    void OnGetSword()
    {
        if (!is_weapon)
        {
            m_weapon.GetComponent<Renderer>().enabled = true;
            is_weapon = true;
            GameObject.FindWithTag("Player").GetComponent<PlayerControl>().SetInvincible(true);
            m_animator.SetTrigger("begin_idle_sword");
        }
    }

    public IEnumerator SwordAutoAttack()
    {
        game_ctrl.OnAttack();
        Vector3 tar_pos = m_attackaTar.position;
        tar_pos.y = transform.position.y;
        transform.LookAt(tar_pos);
        
        yield return null;
        m_animator.SetBool("is_attacking",true);
        m_animator.SetTrigger("begin_attack");
        m_attackaTar.SendMessage("UnderAttack",0);
        yield return new WaitForSeconds(m_attackSpeed);
        game_ctrl.EndAttack();
        Remove();
    }
}
